package com.ruoyi.web.controller.system;

import com.lly835.bestpay.enums.BestPayTypeEnum;
import com.lly835.bestpay.model.PayRequest;
import com.lly835.bestpay.model.PayResponse;
import com.lly835.bestpay.service.impl.BestPayServiceImpl;
import com.lly835.bestpay.utils.JsonUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.json.JSON;
import com.ruoyi.common.json.JSONObject;
import com.ruoyi.common.utils.BeanMapUtils;
import com.ruoyi.common.utils.IdWorker;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.shiro.util.AuthorizationUtils;
import com.ruoyi.system.domain.SysDevice;
import com.ruoyi.system.domain.SysDeviceData;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.service.ISysDeviceDataService;
import com.ruoyi.system.service.ISysDeviceService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 角色信息
 *
 * @author ruoyi
 */
@Slf4j
@Controller
@RequestMapping("/system/device")
public class SysDeviceController extends BaseController
{
    private String prefix = "system/device";

    @Autowired
    private ISysDeviceService deviceService;

    @Autowired
    private ISysDeviceDataService deviceDataService;

    @Autowired
    private BestPayServiceImpl bestPayService;

    @RequiresPermissions("system:device:view")
    @GetMapping()
    public String device()
    {
        return prefix + "/device";
    }

    @RequiresPermissions("system:device:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(SysDevice device)
    {
        startPage();
        List<SysDevice> list = deviceService.selectDeviceList(device);
        return getDataTable(list);
    }

    @Log(title = "设备管理", businessType = BusinessType.EXPORT)
    @RequiresPermissions("system:device:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(SysDevice device)
    {
        List<SysDevice> list = deviceService.selectDeviceList(device);
        ExcelUtil<SysDevice> util = new ExcelUtil<>(SysDevice.class);
        return util.exportExcel(list, "设备列表");
    }

    /**
     * 新增设备
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存设备
     */
    @RequiresPermissions("system:device:add")
    @Log(title = "设备管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated SysDevice device)
    {
        if (UserConstants.ROLE_NAME_NOT_UNIQUE.equals(deviceService.checkDeviceNameUnique(device)))
        {
            return error("新增设备'" + device.getDeviceName() + "'失败，设备名称已存在");
        }
        device.setCreateBy(getLoginName());
        AuthorizationUtils.clearAllCachedAuthorizationInfo();
        return toAjax(deviceService.insertDevice(device));

    }

    /**
     * 修改设备
     */
    @RequiresPermissions("system:device:edit")
    @GetMapping("/edit/{deviceId}")
    public String edit(@PathVariable("deviceId") Long deviceId, ModelMap mmap)
    {
        mmap.put("device", deviceService.selectDeviceById(deviceId));
        return prefix + "/edit";
    }

    /**
     * 修改保存设备
     */
    @RequiresPermissions("system:device:edit")
    @Log(title = "设备管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated SysDevice device)
    {
        if (UserConstants.ROLE_NAME_NOT_UNIQUE.equals(deviceService.checkDeviceNameUnique(device)))
        {
            return error("修改设备'" + device.getDeviceName() + "'失败，设备名称已存在");
        }
        device.setUpdateBy(getLoginName());
        AuthorizationUtils.clearAllCachedAuthorizationInfo();
        return toAjax(deviceService.updateDevice(device));
    }

    @RequiresPermissions("system:device:remove")
    @Log(title = "设备管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(deviceService.deleteDeviceByIds(ids));
    }

    @RequiresPermissions("system:device:detail")
    @GetMapping("/detail/{deviceId}")
    public String detail(@PathVariable("deviceId") Long deviceId, ModelMap mmap)
    {
//        SysDevice device = deviceService.selectDeviceById(deviceId);
        mmap.put("device", deviceService.selectDeviceById(deviceId));
        return prefix + "/detail";
    }

    @RequiresPermissions("system:device:detail")
    @PostMapping("/dataList")
    @ResponseBody
    public TableDataInfo dataList(SysDevice device)
    {
        SysDevice sysDevice = deviceService.selectDeviceById(device.getDeviceId());
        SysDeviceData deviceData = new SysDeviceData();
        deviceData.setDeviceCode(sysDevice.getDeviceCode());
        startPage();
        List<SysDeviceData> list = deviceDataService.selectDeviceList(deviceData);
        return getDataTable(list);
    }

    /**
     * 校验设备名称
     */
    @PostMapping("/checkDeviceNameUnique")
    @ResponseBody
    public String checkRoleNameUnique(SysDevice device)
    {
        return deviceService.checkDeviceNameUnique(device);
    }

    /**
     * 校验设备名称
     */
    @PostMapping("/checkDeviceCodeUnique")
    @ResponseBody
    public String checkDeviceCodeUnique(SysDevice device)
    {
        return deviceService.checkDeviceCodeUnique(device);
    }

    @PostMapping("/queryDeviceList")
    @ResponseBody
    public TableDataInfo queryDeviceList()
    {
        startPage();
        SysDevice sysDevice = new SysDevice();
        sysDevice.setStatus("1");
        List<SysDevice> list = deviceService.selectDeviceList(sysDevice);
        return getDataTable(list);
    }

    /**
     * 修改设备
     */
    @SneakyThrows
    @GetMapping("/purchase/{deviceId}")
    public String purchase(@PathVariable("deviceId") Long deviceId, ModelMap mmap)
    {
        SysDevice device = deviceService.selectDeviceById(deviceId);
//        deviceService.pay(device,getSysUser());
        device.setPhone(getSysUser().getPhonenumber());
        device.setAddress(getSysUser().getAddress());
        mmap.put("device", device);
        return "common/pay";
    }

    /**
     * 发起支付
     */
    @PostMapping(value = "/pay")
    @ResponseBody
    public AjaxResult pay(@RequestParam Long deviceId, @RequestParam String phone, @RequestParam String address, @RequestParam String remark, @RequestParam String payMethod) throws UnsupportedEncodingException {
        //支付请求参数
        SysDevice device = deviceService.selectDeviceById(deviceId);

        String orderId = String.valueOf(new IdWorker().nextId());
//
        PayRequest request = new PayRequest();
        if(payMethod.equals("ali")) {
            request.setPayTypeEnum(BestPayTypeEnum.ALIPAY_PC);
        }else if(payMethod.equals("wx")){
            request.setPayTypeEnum(BestPayTypeEnum.WXPAY_NATIVE);
        }else{
            return AjaxResult.error("请选择支付方式");
        }
        request.setOrderId(orderId);
        Double amount = device.getPrice();
        request.setOrderAmount(amount);
        request.setOrderName(device.getDeviceName());
        request.setAttach(device.getDeviceCode());
        log.info("【发起支付】request={}", JsonUtil.toJson(request));
        PayResponse payResponse = bestPayService.pay(request);
        log.info("【发起支付】response={}", JsonUtil.toJson(payResponse));
        deviceService.pay(device,getSysUser(),orderId,phone,address,amount,remark);
        if(payMethod.equals("ali")) {
            return AjaxResult.success("操作成功", payResponse.getBody().substring(0, 5) + " target='_blank'" + payResponse.getBody().substring(5, payResponse.getBody().length()));
        }else{
            return AjaxResult.success("操作成功", payResponse);
        }
    }

    /**
     * 设备类型
     */
    @PostMapping("/deviceTypeTools")
    @ResponseBody
    public Map<String,Object> deviceTypeTools(@Validated Long deviceId)
    {
        return deviceService.deviceTypeTools(deviceId);
    }
}
